//上传多文件
//var fileArr = [];
layui.use('upload', function(){
    var $ = layui.jquery;
    var upload = layui.upload;
    var size = 1024*10;
    var file_exts = 'txt|pdf|doc|xls|ppt|docx|xlsx|pptx';

    var uploadKey = [],loading = null;
    upload.render({
        elem: '#file-slide-pc',
        url: '/finances/upload/index',
        size: size,
        auto: true,
        accept: 'file',
        exts: file_exts,
        multiple: true,
        before: function(obj) {
            var uploadDir=$('#uploadDir').val();
            this.data = {
                name: uploadDir
            };
            var files = [];
            this.old_files = typeof this.old_files == "undefined" ? [] : this.old_files;// 旧文件
            this.new_files = obj.pushFile(); // 新文件
            this.files_count = 0;//成功处理文件数
            this.deal_files_count = 0;//需要处理文件数

            var fileName;
            // var exts_str = "txt,pdf,doc,xls,ppt,docx,xlsx,pptx";
            for(var key in this.new_files){
                //旧文件已处理
                if( typeof this.old_files[key] != "undefined" ) continue;
                this.old_files[key] = this.new_files[key];
                this.deal_files_count++;

                fileName = this.new_files[key].name; //针对一个文件直接赋值就可以了
                var ext = fileName.substr(fileName.lastIndexOf('.') + 1);//获得后缀
                // 不支持文件类型
                if(file_exts.indexOf(ext) == -1) continue;
                files[key] = this.new_files[key];
                this.files_count++;
            }
            this.files = files;
            if( this.deal_files_count != this.files_count ){
                layer.msg('选择的文件中包含不支持的格式', {
                    icon: 2,
                    shift: 6
                });
                return false;
            }

            loading = layer.msg('文件上传中...', {
                icon: 16,
                shade: 0.01,
                time: 0
            })
        },
        done: function(res,index) {
            // 包含不支持的文件类型
            if( this.deal_files_count != this.files_count ) return false;
            for(var key in this.files) {
                if( $.inArray(key,uploadKey) !== -1 ) continue;
                uploadKey.push(key);

                var fileName = this.files[key].name;
                var ext = fileName.substr(fileName.lastIndexOf('.') + 1);//获得后缀
                var upload_dir_name = res.data.dir + random_string(10) + '.' + ext;
                var request = new FormData();
                request.append("OSSAccessKeyId", res.data.accessid);//Bucket 拥有者的Access Key Id。
                request.append("policy", res.data.policy);//policy规定了请求的表单域的合法性
                request.append("Signature", res.data.signature);//根据Access Key Secret和policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性
                //---以上都是阿里的认证策略
                request.append("key", upload_dir_name);//文件名字，可设置路径
                request.append("success_action_status", '200');// 让服务端返回200,不然，默认会返回204
                // request.append('file', result);//需要上传的文件 file
                request.append('file', this.files[key]);
                request.append("callback", 'oss-cn-hangzhou.aliyuncs.com');//回调，非必选，可以在policy中自定义

                $.ajax({
                    size: size,
                    type: 'post',
                    url: res.data.host,  //上传阿里地址
                    data: request,
                    processData: false,//默认true，设置为 false，不需要进行序列化处理
                    cache: false,//设置为false将不会从浏览器缓存中加载请求信息
                    async: false,//发送同步请求
                    contentType: false,//避免服务器不能正常解析文件---------具体的可以查下这些参数的含义
                    dataType: 'text',//不涉及跨域  写json即可
                    success: function (callbackHost, request) { //callbackHost：success,request中就是 回调的一些信息，包括状态码什么的
                        console.log(request);
                        if (request != 'success') {
                            layer.msg("上传文件出错");
                        }
                        /// ori_files_name 原始文件名
                        $('#file-slide-pc-priview').append(
                            '<li class="item_img"><div class="operate">' +
                            '<i class="closeFile layui-icon"></i></div>' +
                            '<a target="_blank" href="' + res.data.host + upload_dir_name + '">' +
                            '<img src="/static/images/u2669.png">' +
                            '</a>' +
                            '<input type="hidden" name="files[]" value="' + res.data.host + upload_dir_name + '" />' +
                            '<input type="hidden" name="ori_files_name[]" value="' + fileName + '" />' +
                            '</li>'
                        );
                        if(typeof setUploadFileTips == "function") setUploadFileTips();
                    },
                    error: function (returndata) {
                        layer.msg("上传文件出错" + returndata.data);
                    }
                });
            }

            //关闭上传提示窗口
            layer.close(loading);
        },
        allDone: function(obj) {
            // 包含不支持的文件类型
            if( this.deal_files_count != this.files_count ) return false;
            layer.msg('成功上传'+ this.files_count+ '个文件');
        }
    });
});

if(typeof uploadResource != 'function'){
    /**
     * 上传资源文件
     * @param file_exts 支持的文件拓展名；默认 jpg|png|jpeg|txt|pdf|doc|xls|ppt|docx|xlsx|pptx
     * @param uploadBtn 上传按钮元素ID
     * @param imgPriview 图片预览元素ID
     * @param filePriview 文件预览元素ID
     * @param imgsLimit 图片限制个数；默认 0 不限制
     * @param fileLimit 文件限制个数；默认 0 不限制
     * @param acceptMime 筛选出的文件类型
     * @param size 文件大小-kb 0 不限制 -(dyl add 2020.7.16)
     * @param sizeImg 文件大小-kb 0 不限制 -(dyl add 2020.7.16)
     * @param imgExtendFormat 图片文件的扩展格式(自定义) -(dyl add 2020.9.8)
     */
    uploadResource = function (file_exts, uploadBtn, imgPriview, filePriview, imgsLimit, fileLimit, acceptMime, size, sizeImg, imgExtendFormat) {
        var img_exts = 'jpg|png|jpeg';
        file_exts = (typeof file_exts == "undefined" || file_exts == null || file_exts == '') ?  img_exts+ '|'+ 'txt|pdf|doc|xls|ppt|docx|xlsx|pptx' : file_exts;
        uploadBtn = (typeof uploadBtn == "undefined" || uploadBtn == null || uploadBtn == '') ? 'upload-resource' : uploadBtn;
        imgPriview = (typeof imgPriview == "undefined" || imgPriview == null || imgPriview == '') ? 'imgs-resource-priview' : imgPriview;
        filePriview = (typeof filePriview == "undefined" || filePriview == null || filePriview == '') ? 'files-resource-priview' : filePriview;
        imgsLimit = (typeof imgsLimit == "undefined" || imgsLimit == null || imgsLimit == '') ? 0 : imgsLimit;
        fileLimit = (typeof fileLimit == "undefined" || fileLimit == null || fileLimit == '') ? 0 : fileLimit;
        acceptMime = (typeof acceptMime == "undefined" || acceptMime == null || acceptMime == '') ? '*' : acceptMime;

        var size1 = (typeof size != "undefined" && size != null) ? size : 1024*10;                  //(dyl add 2020.7.16)
        var sizeImg1 = (typeof sizeImg != "undefined" && sizeImg != null) ? sizeImg : 1024*6;       //(dyl add 2020.7.16)

        file_exts += '|' + file_exts.toLocaleUpperCase();
        img_exts += '|' + img_exts.toLocaleUpperCase();

        //(dyl add 2020.9.8)
        if (typeof imgExtendFormat != "undefined" && imgExtendFormat != null) {
            img_exts = imgExtendFormat.toLocaleLowerCase() + '|' + imgExtendFormat.toLocaleUpperCase();
        }

        //console.log(size1);
        //console.log(sizeImg1);

        var alreadyImgsC = $('#'+imgPriview).find('img').length;
        var alreadyFilesC = $('#'+filePriview).find('img').length;
        layui.use('upload', function(){
            var $ = layui.jquery;
            var upload = layui.upload;
            //var size = 1024*10;
            var size = size1;           //(dyl modify 2020.7.16)
            //var sizeImg = 1024*6;
            var sizeImg = sizeImg1;     //(dyl modify 2020.7.16)
            var uploadKey = [],loading = null;
            upload.render({
                elem: '#' + uploadBtn,
                url: '/finances/upload/index',
                size: size,
                auto: true,
                accept: 'file',
                acceptMime: acceptMime,
                exts: file_exts,
                multiple: true,
                before: function(obj) {
                    var uploadDir = $('#uploadDir').val();
                    this.data = {
                        name: uploadDir
                    };
                    var files = [];
                    this.old_files = typeof this.old_files == "undefined" ? [] : this.old_files;// 旧文件
                    this.new_files = obj.pushFile(); // 新文件
                    this.files_count = 0;//成功处理文件数
                    this.deal_files_count = 0;//需要处理文件数

                    alreadyImgsC = $('#'+imgPriview).find('img').length;
                    alreadyFilesC = $('#'+filePriview).find('img').length;
                    var fileName = '',errorMsg = '',imgsCount = alreadyImgsC,filesCount = alreadyFilesC;
                    for(var key in this.new_files){
                        //旧文件已处理
                        if( typeof this.old_files[key] != "undefined" ) continue;
                        this.old_files[key] = this.new_files[key];
                        this.deal_files_count++;

                        fileName = this.new_files[key].name; //针对一个文件直接赋值就可以了
                        var ext = fileName.substr(fileName.lastIndexOf('.') + 1);//获得后缀
                        // 不支持文件类型
                        if(file_exts.indexOf(ext) == -1){
                            errorMsg = '选择的文件中包含不支持的格式';
                            continue;
                        }
                        //图片类型
                        //if ($.inArray(ext, img_exts.split('|')) >= 0 ) {
                        if ($.inArray(ext, img_exts.split('|')) >= 0 && sizeImg > 0) {      //(dyl modify 2020.7.16)
                            if(this.new_files[key].size > sizeImg * 1024){
                                errorMsg = '图片文件不能超过6M';
                                continue;
                            }
                            imgsCount++;
                            if(imgsLimit > 0 && imgsCount > imgsLimit){
                                errorMsg = '只能上传'+ imgsLimit +'张图片';
                                continue;
                            }
                        }else{
                            filesCount++;
                            if(fileLimit > 0 && filesCount > fileLimit){
                                errorMsg = '只能上传'+ fileLimit +'个文件';
                                continue;
                            }
                        }

                        files[key] = this.new_files[key];
                        this.files_count++;
                    }
                    this.files = files;
                    if( this.deal_files_count != this.files_count ){
                        layer.msg(errorMsg, {
                            icon: 2,
                            shift: 6
                        });
                        return false;
                    }

                    loading = layer.msg('资源上传中...', {
                        icon: 16,
                        shade: 0.01,
                        time: 0
                    })
                },
                done: function(res,index) {
                    // 包含不支持的文件类型
                    if( this.deal_files_count != this.files_count ) return false;
                    for(var key in this.files) {
                        if( $.inArray(key,uploadKey) !== -1 ) continue;
                        uploadKey.push(key);

                        var fileName = this.files[key].name;
                        var ext = fileName.substr(fileName.lastIndexOf('.') + 1);//获得后缀
                        var upload_dir_name = res.data.dir + random_string(10) + '.' + ext;
                        var request = new FormData();
                        request.append("OSSAccessKeyId", res.data.accessid);//Bucket 拥有者的Access Key Id。
                        request.append("policy", res.data.policy);//policy规定了请求的表单域的合法性
                        request.append("Signature", res.data.signature);//根据Access Key Secret和policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性
                        //---以上都是阿里的认证策略
                        request.append("key", upload_dir_name);//文件名字，可设置路径
                        request.append("success_action_status", '200');// 让服务端返回200,不然，默认会返回204
                        // request.append('file', result);//需要上传的文件 file
                        request.append('file', this.files[key]);
                        request.append("callback", 'oss-cn-hangzhou.aliyuncs.com');//回调，非必选，可以在policy中自定义

                        $.ajax({
                            size: size,
                            type: 'post',
                            url: res.data.host,  //上传阿里地址
                            data: request,
                            processData: false,//默认true，设置为 false，不需要进行序列化处理
                            cache: false,//设置为false将不会从浏览器缓存中加载请求信息
                            async: false,//发送同步请求
                            contentType: false,//避免服务器不能正常解析文件---------具体的可以查下这些参数的含义
                            dataType: 'text',//不涉及跨域  写json即可
                            success: function (callbackHost, request) { //callbackHost：success,request中就是 回调的一些信息，包括状态码什么的
                                if (request != 'success') {
                                    layer.msg("上传资源文件出错");return false;
                                }

                                if ($.inArray(ext, img_exts.split('|')) >= 0) {
                                    $('#' + imgPriview).append('<li class="item_img"><div class="operate"><i class="toleft layui-icon">' +
                                        '</i><i class="toright layui-icon"></i><i  class="close layui-icon"></i></div>' +
                                        '<img src=' + res.data.host+upload_dir_name+' class="img" ><input type="hidden" name="imgs[]" value="'+ res.data.host+upload_dir_name + '" /></li>');
                                }else{
                                    /// ori_files_name 原始文件名
                                    $('#' + filePriview).append(
                                        '<li class="item_img"><div class="operate">' +
                                        '<i class="closeFile layui-icon"></i></div>' +
                                        '<a target="_blank" href="' + res.data.host + upload_dir_name + '">' +
                                        '<img src="/static/images/u2669.png">' +
                                        '</a>' +
                                        '<input type="hidden" name="files[]" value="' + res.data.host + upload_dir_name + '" />' +
                                        '<input type="hidden" name="ori_files_name[]" value="' + fileName + '" />' +
                                        '</li>'
                                    );
                                }
                                if(typeof setImgSize == "function") setImgSize('#'+imgPriview +' img');
                                if(typeof setUploadFileTips == "function") setUploadFileTips();
                            },
                            error: function (returndata) {
                                layer.msg("上传资源文件出错" + returndata.data);
                            }
                        });
                    }

                    //关闭上传提示窗口
                    layer.close(loading);
                },
                allDone: function(obj) {
                    // 包含不支持的文件类型
                    if( this.deal_files_count != this.files_count ) return false;
                    layer.msg('成功上传'+ this.files_count+ '个资源文件');
                }
            });
        });
    }
}

//点击多图上传的X,删除当前的图片
$("body").on("click",".closeFile",function(){
    $(this).closest("li").remove();
});

/**
 * 页面加载需要执行上传文件相关函数
 * @author:Allan
 */
$(document).ready(function () {
    if(typeof setUploadFileTips == "function") setUploadFileTips();
});

var tip_index = null;
$(document).on('mouseenter', '.file-more li.item_img', function () {
    var obj = this;
    var msg = $(obj).attr('data-tips');
    if(typeof msg == "undefined" || msg == null || msg == '') return false;
    tip_index = layer.tips(msg, obj, {
        tipsMore: true,
        time: 0,
        tips: 3
    });

}).on('mouseleave', ' .file-more li.item_img', function () {
    if(tip_index) layer.close(tip_index);
}).on('click','.closeFile,.close',function(){
    if(tip_index) layer.close(tip_index);
});


if(typeof setUploadFileTips != 'function'){
    /**
     * 设置上传文件名称提示
     * @author:Allan
     * @param obj
     * @param winWidth
     * @param winHeight
     */
    function setUploadFileTips(obj){
        obj = typeof obj != 'object' ? $('.file-more li.item_img') : obj;
        obj.each(function(){
            var obj =  $(this);
            var file_name = obj.find('input[name="ori_files_name[]"]').val();
            // console.log(file_url,'file_url')
            // var resourse = file_url.split('/');
            // var file_name = resourse[resourse.length-1];
            // console.log(file_name,'file_name')
            obj.attr('data-tips',file_name);
        })
    }
}